package com.ywl.stream;

import com.ywl.entity.Author;
import com.ywl.utils.AuthorFactory;

import java.util.List;
import java.util.Optional;


/**
 * Stream流中的reduce
 *
 * @author 24040
 * @name StreamDemo08
 * @date 2022-08-22 15:31
 */
public class StreamDemo08 {
    public static void main(String[] args) {
        test01();
        test02();
        test03();
        test04();
    }

    /**
     * 使用reduce求所有作者年龄的和
     */
    public static void test01() {
        List<Author> authors = AuthorFactory.getAuthors();
       /* authors.stream()
                .map(author -> author.getAge())
                .reduce(0, new BinaryOperator<Integer>() {
                    @Override
                    *//**
         * result 为要进行累加的值，element为
         * @return 返回的是累加之后的值，并且会赋给该接口中的identity元素
         *//*
                    public Integer apply(Integer result, Integer element) {
                        return result + element;
                    }
                });*/
        Integer reduce = authors.stream()
                .map(author -> author.getAge())
                .reduce(0, (result, element) -> result + element);
        System.out.println(reduce);
    }

    /**
     * 使用reduce求所有作者中年龄的最大值
     */
    public static void test02() {
        List<Author> authors = AuthorFactory.getAuthors();

        Integer max = authors.stream()
                .map(author -> author.getAge())
                .reduce(Integer.MIN_VALUE, (result, element) -> result < element ? element : result);
        System.out.println(max);
    }

    /**
     * 使用reduce求所有作者中年龄的最小值
     */
    public static void test03() {
        List<Author> authors = AuthorFactory.getAuthors();

        Integer min = authors.stream()
                .map(author -> author.getAge())
                .reduce(Integer.MAX_VALUE, (result, element) -> result > element ? element : result);
        System.out.println(min);
    }

    /**
     * 使用reduce 一个参数
     */
    public static void test04() {
        List<Author> authors = AuthorFactory.getAuthors();
        Optional<Integer> min = authors.stream()
                .map(author -> author.getAge())
                .reduce((result, element) -> result > element ? element : result);
        System.out.println(min.get());
    }

}
